import { defineStore } from 'pinia';
import { userApi } from '@/services/api';

export const useUserStore = defineStore('user', {
  state: () => {
    // 安全地解析 localStorage 中的用户数据
    const userDataStr = localStorage.getItem('userData');
    let userData = null;
    if (userDataStr) {
      try {
        userData = JSON.parse(userDataStr);
      } catch (e) {
        console.error('解析用户数据失败:', e);
        // 清除无效的数据
        localStorage.removeItem('userData');
      }
    }
    
    return {
      user: userData,
      token: localStorage.getItem('userToken') || null,
      loading: false,
      error: null,
      bookmarks: [],
      notes: [],
      progress: {},
    };
  },
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    getUser: (state) => state.user,
    getUserId: (state) => state.user?._id,
    getUsername: (state) => state.user?.username,
    getBookmarks: (state) => state.bookmarks,
    getNotes: (state) => state.notes,
    getProgress: (state) => state.progress,
  },
  
  actions: {
    // 用户注册
    async register(userData) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await userApi.register(userData);
        const { token, user } = response.data;
        
        this.user = user;
        this.token = token;
        
        localStorage.setItem('userToken', token);
        // 安全地存储用户数据
        if (user) {
          try {
            localStorage.setItem('userData', JSON.stringify(user));
          } catch (e) {
            console.error('存储用户数据失败:', e);
          }
        }
        
        return { success: true, user };
      } catch (error) {
        this.error = error.response?.data?.message || '注册失败';
        // 返回更详细的错误信息
        return { 
          success: false, 
          error: this.error,
          details: error.response?.data?.errors || error.response?.data?.details
        };
      } finally {
        this.loading = false;
      }
    },
    
    // 用户登录
    async login(credentials) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await userApi.login(credentials);
        const { token, user } = response.data;
        
        this.user = user;
        this.token = token;
        
        localStorage.setItem('userToken', token);
        // 安全地存储用户数据
        if (user) {
          try {
            localStorage.setItem('userData', JSON.stringify(user));
          } catch (e) {
            console.error('存储用户数据失败:', e);
          }
        }
        
        return { success: true, user };
      } catch (error) {
        this.error = error.response?.data?.message || '登录失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 用户登出
    logout() {
      this.user = null;
      this.token = null;
      this.bookmarks = [];
      this.notes = [];
      this.progress = {};
      
      try {
        localStorage.removeItem('userToken');
        localStorage.removeItem('userData');
      } catch (e) {
        console.error('清除用户数据失败:', e);
      }
    },
    
    // 获取用户资料
    async fetchProfile() {
      if (!this.token) return;
      
      this.loading = true;
      this.error = null;
      
      try {
        const response = await userApi.getProfile();
        this.user = response.data;
        
        // 安全地存储用户数据
        if (this.user) {
          try {
            localStorage.setItem('userData', JSON.stringify(this.user));
          } catch (e) {
            console.error('存储用户资料失败:', e);
          }
        }
        
        return { success: true, user: this.user };
      } catch (error) {
        this.error = error.response?.data?.message || '获取用户资料失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 更新用户资料
    async updateProfile(userData) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await userApi.updateProfile(userData);
        this.user = response.data;
        
        // 安全地存储用户数据
        if (this.user) {
          try {
            localStorage.setItem('userData', JSON.stringify(this.user));
          } catch (e) {
            console.error('存储用户资料失败:', e);
          }
        }
        
        return { success: true, user: this.user };
      } catch (error) {
        this.error = error.response?.data?.message || '更新用户资料失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 获取用户书签
    async fetchBookmarks() {
      if (!this.token) return { success: false, error: '未登录' };
      
      this.loading = true;
      this.error = null;
      
      try {
        console.log('[fetchBookmarks] 开始获取用户书签');
        const response = await userApi.getBookmarks();
        console.log('[fetchBookmarks] 获取书签结果:', response.data);
        
        // 确保书签数据格式正确
        this.bookmarks = response.data.map(bookmark => ({
          cardId: bookmark._id,
          title: bookmark.title,
          content: bookmark.content,
          chapter: bookmark.chapter,
          difficulty: bookmark.difficulty,
          tags: bookmark.tags,
          sourceDocument: bookmark.sourceDocument,
          createdAt: bookmark.createdAt
        }));
        
        console.log(`[fetchBookmarks] 成功获取 ${this.bookmarks.length} 个书签`);
        
        return { success: true, bookmarks: this.bookmarks };
      } catch (error) {
        console.error('[fetchBookmarks] 获取书签失败:', error);
        this.error = error.response?.data?.message || '获取书签失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 添加书签
    async addBookmark(cardId) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await userApi.addBookmark(cardId);
        await this.fetchBookmarks(); // 重新获取书签列表
        
        return { success: true, bookmark: response.data };
      } catch (error) {
        this.error = error.response?.data?.message || '添加书签失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 移除书签
    async removeBookmark(cardId) {
      this.loading = true;
      this.error = null;
      
      try {
        await userApi.removeBookmark(cardId);
        this.bookmarks = this.bookmarks.filter(bookmark => bookmark.cardId !== cardId);
        
        return { success: true };
      } catch (error) {
        this.error = error.response?.data?.message || '移除书签失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 获取用户笔记
    async fetchNotes() {
      if (!this.token) return;
      
      this.loading = true;
      this.error = null;
      
      try {
        const response = await userApi.getNotes();
        this.notes = response.data;
        
        return { success: true, notes: this.notes };
      } catch (error) {
        this.error = error.response?.data?.message || '获取笔记失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 添加笔记
    async addNote(noteData) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await userApi.addNote(noteData);
        await this.fetchNotes(); // 重新获取笔记列表
        
        return { success: true, note: response.data };
      } catch (error) {
        this.error = error.response?.data?.message || '添加笔记失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 更新笔记
    async updateNote(noteId, content) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await userApi.updateNote(noteId, content);
        
        // 更新本地笔记
        const index = this.notes.findIndex(note => note._id === noteId);
        if (index !== -1) {
          this.notes[index] = response.data;
        }
        
        return { success: true, note: response.data };
      } catch (error) {
        this.error = error.response?.data?.message || '更新笔记失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 删除笔记
    async deleteNote(noteId) {
      this.loading = true;
      this.error = null;
      
      try {
        await userApi.deleteNote(noteId);
        this.notes = this.notes.filter(note => note._id !== noteId);
        
        return { success: true };
      } catch (error) {
        this.error = error.response?.data?.message || '删除笔记失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 更新学习进度
    async updateProgress(progressData) {
      this.loading = true;
      this.error = null;
      
      try {
        const response = await userApi.updateProgress(progressData);
        
        // 更新本地进度
        this.progress = {
          ...this.progress,
          [progressData.cardId]: response.data
        };
        
        return { success: true, progress: response.data };
      } catch (error) {
        this.error = error.response?.data?.message || '更新学习进度失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
    
    // 获取学习报告
    async fetchLearningReport() {
      if (!this.token) return;
      
      this.loading = true;
      this.error = null;
      
      try {
        const response = await userApi.getLearningReport();
        
        return { success: true, report: response.data };
      } catch (error) {
        this.error = error.response?.data?.message || '获取学习报告失败';
        return { success: false, error: this.error };
      } finally {
        this.loading = false;
      }
    },
  },
}); 